package com.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.gulimall.product.dao.CategoryBrandRelationDao;
import com.gulimall.product.entity.CategoryBrandRelationEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.gulimall.product.dao.BrandDao;
import com.gulimall.product.entity.BrandEntity;
import com.gulimall.product.service.BrandService;

import javax.annotation.Resource;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Resource
    private BrandDao brandDao;
    @Resource
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(key)){
            wrapper.like("name",key).or().eq("brand_id",key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<BrandEntity> queryBrandByCatId(Long catId) {
        // 1、查出当前分组下所有关系数据集合
        List<CategoryBrandRelationEntity> relationList = categoryBrandRelationDao.selectList(new QueryWrapper<CategoryBrandRelationEntity>().eq("catelog_id", catId));
        // 2、通过集合来筛选出对应的品牌ID集合
        List<Long> brandIdList = relationList.stream().map(CategoryBrandRelationEntity::getBrandId).collect(Collectors.toList());
        // 3、查出对应的品牌对象集合
        if(brandIdList.size() > 0){
            return brandDao.selectList(new QueryWrapper<BrandEntity>().in("brand_id",brandIdList));
        }
        // 如果品牌ID为空直接返回null
        return null;
    }

}